package org.example.custom.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.example.custom.annotation.MyDS;
import org.example.custom.utils.DatasourceContextHolder;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;

@Aspect
@Component
public class MyDSAspect {

    //定义切入点
    @Pointcut("@annotation(org.example.custom.annotation.MyDS)")
    public void pointCut() {}


    //拦截切点并环绕增强
    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        String defaultDataSource = "order";

        //获取当前执行方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        //获取方法上MyDS注解
        MyDS myDS = method.getAnnotation(MyDS.class);

        //方法上如果有配置数据源则使用指定的数据源
        if (Objects.nonNull(myDS)) {
            defaultDataSource = myDS.value();
        }

        //设置数据源到用户线程上下文中
        DatasourceContextHolder.setContext(defaultDataSource);

        try{
            //执行目标方法
            return joinPoint.proceed();
        }finally {
            //清除用户线程上下文中数据源
            DatasourceContextHolder.clearContext();
        }

    }


}
